<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />





  <link rel="alternate" href="/atom.xml" title="yampery" type="application/atom+xml" />






<meta name="description" content="本文并非详细探讨AES加解密内容，而是在Spring+Mybatis的项目基础上，以sql拦截器的形式，实现了对数据存取加解密的方案。文章项目示例采用springboot框架，对需要加解密的字段添加注解，sql执行过程中，拦截器进行拦截。可通过配置加解密开关决定是否对字段进行加解密。加密方式AES。  文章并未列出所有源码，依赖包等详细配置，在源码中有具体的sql脚本等文件，点击访问项目源码。">
<meta property="og:type" content="article">
<meta property="og:title" content="使用拦截器进行数据加解密">
<meta property="og:url" content="http://yampery.github.io/2019/01/05/cryptic_interceptor/index.html">
<meta property="og:site_name" content="yampery">
<meta property="og:description" content="本文并非详细探讨AES加解密内容，而是在Spring+Mybatis的项目基础上，以sql拦截器的形式，实现了对数据存取加解密的方案。文章项目示例采用springboot框架，对需要加解密的字段添加注解，sql执行过程中，拦截器进行拦截。可通过配置加解密开关决定是否对字段进行加解密。加密方式AES。  文章并未列出所有源码，依赖包等详细配置，在源码中有具体的sql脚本等文件，点击访问项目源码。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-01-30T01:28:52.520Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用拦截器进行数据加解密">
<meta name="twitter:description" content="本文并非详细探讨AES加解密内容，而是在Spring+Mybatis的项目基础上，以sql拦截器的形式，实现了对数据存取加解密的方案。文章项目示例采用springboot框架，对需要加解密的字段添加注解，sql执行过程中，拦截器进行拦截。可通过配置加解密开关决定是否对字段进行加解密。加密方式AES。  文章并未列出所有源码，依赖包等详细配置，在源码中有具体的sql脚本等文件，点击访问项目源码。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yampery.github.io/2019/01/05/cryptic_interceptor/"/>





  <title>使用拦截器进行数据加解密 | yampery</title>
  








  <link href='//fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">yampery</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天尽头，回眸望红尘</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yampery.github.io/2019/01/05/cryptic_interceptor/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yampery">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="yampery">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">使用拦截器进行数据加解密</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-05T14:47:07+08:00">
                2019-01-05
              </time>
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2019/01/05/cryptic_interceptor/" class="leancloud_visitors" data-flag-title="使用拦截器进行数据加解密">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.7k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  13 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本文并非详细探讨AES加解密内容，而是在Spring+Mybatis的项目基础上，以sql拦截器的形式，实现了对数据存取加解密的方案。文章项目示例采用springboot框架，对需要加解密的字段添加注解，sql执行过程中，拦截器进行拦截。可通过配置加解密开关决定是否对字段进行加解密。加密方式AES。</p>
</blockquote>
<p>文章并未列出所有源码，依赖包等详细配置，在源码中有具体的sql脚本等文件，<a href="https://github.com/Yampery/cryptic-data" target="_blank" rel="noopener">点击访问项目源码。</a></p>
<ul>
<li>源码框架<blockquote>
<p>java8   springboot   mybatis   gradle</p>
</blockquote>
</li>
</ul>
<hr>
<h2 id="加解密工具"><a href="#加解密工具" class="headerlink" title="加解密工具"></a>加解密工具</h2><blockquote>
<p>方法generateAESKey()生成128位秘钥，以16进制字符串保存，从配置文件读取，以单例模式初始化加解密工具，保证项目运行过程中对象不会被重新创建，避免多次初始化Cipher。加解密方法详见代码如下。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@decription</span> ADESUtils</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;字段加解密，使用MySql AES算法&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Yampery</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2018/4/4 13:10</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ADESUtils</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String ENCRYPT_TYPE = <span class="string">"AES"</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String ENCODING = <span class="string">"UTF-8"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 密盐</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> String aesSalt;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ADESUtils adesUtils;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Cipher encryptCipher;    <span class="comment">// 加密cipher</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Cipher decryptChipher;   <span class="comment">// 解密chipher</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 加解密开关，从配置获取</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> String CRYPTIC_SWITCH;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 从配置中获取秘钥</span></span><br><span class="line"><span class="comment">     * :默认值填写自己生成的秘钥</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;sys.aes.salt:0&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAESSalt</span><span class="params">(String key)</span></span>&#123;</span><br><span class="line">        ADESUtils.aesSalt = key;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取开关</span></span><br><span class="line"><span class="comment">     * 默认为不加密</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> val</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;sys.aes.switch:0&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCrypticSwitch</span><span class="params">(String val)</span> </span>&#123;</span><br><span class="line">        ADESUtils.CRYPTIC_SWITCH = val;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * encryptCipher、decryptChipher初始化</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            encryptCipher = Cipher.getInstance(ENCRYPT_TYPE);</span><br><span class="line">            decryptChipher = Cipher.getInstance(ENCRYPT_TYPE);</span><br><span class="line">            encryptCipher.init(Cipher.ENCRYPT_MODE, generateMySQLAESKey(aesSalt));</span><br><span class="line">            decryptChipher.init(Cipher.DECRYPT_MODE, generateMySQLAESKey(aesSalt));</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InvalidKeyException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NoSuchAlgorithmException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NoSuchPaddingException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">ADESUtils</span><span class="params">()</span> </span>&#123;  &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取单例</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ADESUtils <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(adesUtils == <span class="keyword">null</span>)&#123;</span><br><span class="line">            <span class="comment">// 当需要创建的时候在加锁</span></span><br><span class="line">            <span class="keyword">synchronized</span>(ADESUtils.class) &#123;</span><br><span class="line">                <span class="keyword">if</span> (adesUtils == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    adesUtils = <span class="keyword">new</span> ADESUtils();</span><br><span class="line">                    init();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> adesUtils;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 对明文加密</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> pString</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">encrypt</span><span class="params">(String pString)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (StringUtils.isBlank(pString) || StringUtils.equals(<span class="string">"0"</span>, CRYPTIC_SWITCH))</span><br><span class="line">            <span class="keyword">return</span> StringUtils.trimToEmpty(pString);</span><br><span class="line">        <span class="keyword">try</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> String(Hex.encodeHex(encryptCipher.doFinal(pString.getBytes(ENCODING)))).toUpperCase();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            <span class="keyword">return</span> pString;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 对密文解密</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> eString</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">decrypt</span><span class="params">(String eString)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (StringUtils.isBlank(eString) || StringUtils.equals(<span class="string">"0"</span>, CRYPTIC_SWITCH))</span><br><span class="line">            <span class="keyword">return</span> StringUtils.trimToEmpty(eString);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> String(decryptChipher.doFinal(Hex.decodeHex(eString.toCharArray())));</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            <span class="keyword">return</span> eString;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 产生mysql-aes_encrypt</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key 加密的密盐</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> SecretKeySpec <span class="title">generateMySQLAESKey</span><span class="params">(<span class="keyword">final</span> String key)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">final</span> <span class="keyword">byte</span>[] finalKey = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">16</span>];</span><br><span class="line">            <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">byte</span> b : Hex.decodeHex(key.toCharArray()))</span><br><span class="line">                finalKey[i++ % <span class="number">16</span>] ^= b;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> SecretKeySpec(finalKey, <span class="string">"AES"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span>(Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 生成秘钥(128位)</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">generateAESKey</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">        <span class="comment">//实例化</span></span><br><span class="line">        KeyGenerator kgen = KeyGenerator.getInstance(<span class="string">"AES"</span>);</span><br><span class="line">        <span class="comment">//设置密钥长度</span></span><br><span class="line">        kgen.init(<span class="number">128</span>);</span><br><span class="line">        <span class="comment">//生成密钥</span></span><br><span class="line">        SecretKey skey = kgen.generateKey();</span><br><span class="line">        <span class="comment">// 转为16进制字串</span></span><br><span class="line">        String key = <span class="keyword">new</span> String(Hex.encodeHex(skey.getEncoded()));</span><br><span class="line">        <span class="comment">//返回密钥的16进制字串</span></span><br><span class="line">        <span class="keyword">return</span> key.toUpperCase();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="加解密字段注解"><a href="#加解密字段注解" class="headerlink" title="加解密字段注解"></a>加解密字段注解</h2><blockquote>
<p>注解标识字段是否需要加密或者解密，用于通过反射获取需要进行加解密的字段，防止需求变动，将加密和解密注解分开。</p>
</blockquote>
<h3 id="加密注解"><a href="#加密注解" class="headerlink" title="加密注解"></a>加密注解</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@decription</span> EncryptField</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;字段加密注解&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Yampery</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/10/24 13:01</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Target</span>(ElementType.FIELD)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> EncryptField &#123;</span><br><span class="line">    <span class="function">String <span class="title">value</span><span class="params">()</span> <span class="keyword">default</span> ""</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="解密注解"><a href="#解密注解" class="headerlink" title="解密注解"></a>解密注解</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@decription</span> DecryptField</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;字段解密注解&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Yampery</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/10/24 13:05</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Target</span>(ElementType.FIELD)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> DecryptField &#123;</span><br><span class="line">    <span class="function">String <span class="title">value</span><span class="params">()</span> <span class="keyword">default</span> ""</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="封装加解密工具"><a href="#封装加解密工具" class="headerlink" title="封装加解密工具"></a>封装加解密工具</h2><blockquote>
<p>为了在项目中方便使用，将上节中的加解密工具进行封装，封装后的工具可以作用于对象，通过反射获取注解，而对原对象进行改变。另外，项目中也实现了对象的自加解密CrypticPojo，原理是CrypticPojo实现clone方法，并在内部实现加解密方法，需要进行字段加解密的业务对象只需要继承CrypticPojo，每次返回调用一次克隆并加密方法即可，具体见源码。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@decription</span> CryptPojoUtils</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;对象加解密工具</span></span><br><span class="line"><span class="comment"> * 其子类可以通过调用&lt;tt&gt;encrypt(T t)&lt;/tt&gt;方法实现自加密，返回参数类型；</span></span><br><span class="line"><span class="comment"> * 调用&lt;tt&gt;decrypt(T t)&lt;/tt&gt;实现自解密，返回参数类型；</span></span><br><span class="line"><span class="comment"> * &lt;tt&gt;encrypt&lt;/tt&gt;对注解&#123;<span class="doctag">@link</span> EncryptField&#125;字段有效；</span></span><br><span class="line"><span class="comment"> * &lt;tt&gt;decrypt&lt;/tt&gt;对注解&#123;<span class="doctag">@link</span> DecryptField&#125;字段有效。&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Yampery</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/10/24 13:36</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CryptPojoUtils</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 对对象t加密</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> t</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">T <span class="title">encrypt</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line">        Field[] declaredFields = t.getClass().getDeclaredFields();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (declaredFields != <span class="keyword">null</span> &amp;&amp; declaredFields.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">for</span> (Field field : declaredFields) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (field.isAnnotationPresent(EncryptField.class) &amp;&amp; field.getType().toString().endsWith(<span class="string">"String"</span>)) &#123;</span><br><span class="line">                        field.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">                        String fieldValue = (String) field.get(t);</span><br><span class="line">                        <span class="keyword">if</span> (StringUtils.isNotEmpty(fieldValue)) &#123;</span><br><span class="line">                            field.set(t, ADESUtils.getInstance().encrypt(fieldValue));</span><br><span class="line">                        &#125;</span><br><span class="line">                        field.setAccessible(<span class="keyword">false</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IllegalAccessException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> t;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 对象解密</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> t</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">T <span class="title">decrypt</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line">        Field[] declaredFields = t.getClass().getDeclaredFields();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (declaredFields != <span class="keyword">null</span> &amp;&amp; declaredFields.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">for</span> (Field field : declaredFields) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (field.isAnnotationPresent(DecryptField.class) &amp;&amp; field.getType().toString().endsWith(<span class="string">"String"</span>)) &#123;</span><br><span class="line">                        field.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">                        String fieldValue = (String)field.get(t);</span><br><span class="line">                        <span class="keyword">if</span>(StringUtils.isNotEmpty(fieldValue)) &#123;</span><br><span class="line">                            field.set(t, ADESUtils.getInstance().decrypt(fieldValue));</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IllegalAccessException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> t;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 对含注解字段解密</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> t</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">decryptField</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line">        Field[] declaredFields = t.getClass().getDeclaredFields();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (declaredFields != <span class="keyword">null</span> &amp;&amp; declaredFields.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">for</span> (Field field : declaredFields) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (field.isAnnotationPresent(DecryptField.class) &amp;&amp; field.getType().toString().endsWith(<span class="string">"String"</span>)) &#123;</span><br><span class="line">                        field.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">                        String fieldValue = (String)field.get(t);</span><br><span class="line">                        <span class="keyword">if</span>(StringUtils.isNotEmpty(fieldValue)) &#123;</span><br><span class="line">                            field.set(t, ADESUtils.getInstance().decrypt(fieldValue));</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IllegalAccessException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// return t;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 对含注解字段加密</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> t</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">encryptField</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line">        Field[] declaredFields = t.getClass().getDeclaredFields();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (declaredFields != <span class="keyword">null</span> &amp;&amp; declaredFields.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">for</span> (Field field : declaredFields) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (field.isAnnotationPresent(EncryptField.class) &amp;&amp; field.getType().toString().endsWith(<span class="string">"String"</span>)) &#123;</span><br><span class="line">                        field.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">                        String fieldValue = (String)field.get(t);</span><br><span class="line">                        <span class="keyword">if</span>(StringUtils.isNotEmpty(fieldValue)) &#123;</span><br><span class="line">                            field.set(t, ADESUtils.getInstance().encrypt(fieldValue));</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IllegalAccessException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 隐藏号码中间4位</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> t</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">hidePhone</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line">        Field[] declaredFields = t.getClass().getDeclaredFields();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (declaredFields != <span class="keyword">null</span> &amp;&amp; declaredFields.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">for</span> (Field field : declaredFields) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (field.isAnnotationPresent(DecryptField.class) &amp;&amp; field.getType().toString().endsWith(<span class="string">"String"</span>)) &#123;</span><br><span class="line">                        field.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">                        String fieldValue = (String)field.get(t);</span><br><span class="line">                        <span class="keyword">if</span>(StringUtils.isNotEmpty(fieldValue)) &#123;</span><br><span class="line">                            <span class="comment">// 暂时与解密注解共用一个注解，该注解隐藏手机号中间四位</span></span><br><span class="line">                            field.set(t, StringUtils.overlay(fieldValue, <span class="string">"****"</span>, <span class="number">3</span>, <span class="number">7</span>));</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IllegalAccessException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="拦截器"><a href="#拦截器" class="headerlink" title="拦截器"></a>拦截器</h2><blockquote>
<p>使用sql拦截器处理加解密基本是对项目影响比较小的。该拦截器通过拦截sql，对写入数据和查询结果进行重写，然后再放行从而更改对象。
关于sql语句参数，文章中并没有在拦截器处理，而是使用一个LinkedMap封装了查询参数，在封装的过程中会对字段进行加密。
关于springboot中和spring中拦截器使用的区别下文将会介绍。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@decription</span> DBInterceptor</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;实现Mybatis拦截器，用于拦截修改，插入和返回需要加密或者解密的对象&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Yampery</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2018/4/4 14:17</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Intercepts</span>(&#123;</span><br><span class="line">        <span class="meta">@Signature</span>(type=Executor.class,method=<span class="string">"update"</span>,args=&#123;MappedStatement.class,Object.class&#125;),</span><br><span class="line">        <span class="meta">@Signature</span>(type=Executor.class,method=<span class="string">"query"</span>,args=&#123;MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class&#125;)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DBInterceptor</span> <span class="keyword">implements</span> <span class="title">Interceptor</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(DBInterceptor.class);</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;sys.aes.switch&#125;"</span>) <span class="keyword">private</span> String CRYPTIC_SWITCH;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Invocation invocation)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        MappedStatement statement = (MappedStatement) invocation.getArgs()[<span class="number">0</span>];</span><br><span class="line">        String methodName = invocation.getMethod().getName();</span><br><span class="line">        Object parameter = invocation.getArgs()[<span class="number">1</span>];</span><br><span class="line">        BoundSql sql = statement.getBoundSql(parameter);</span><br><span class="line">        logger.info(<span class="string">"sql is: &#123;&#125;"</span>, sql.getSql());</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@TODO</span> 处理查询</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">if</span> (StringUtils.equalsIgnoreCase(<span class="string">"query"</span>, methodName)) &#123;</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * 在这里可以处理查询参数，如传递的参数为明文，要按照密文查询</span></span><br><span class="line"><span class="comment">             * 本文选择使用同一参数封装处理方案&#123;<span class="doctag">@link</span> git.yampery.cryptic.common.QueryParams&#125;</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 拦截批量插入操作不仅繁琐，而且为了通用逐一通过反射加密不妥</span></span><br><span class="line"><span class="comment">         * 如果有批量操作，最好在传递参数之前，向list中添加之前就加密</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">if</span> (!<span class="string">"0"</span>.equals(CRYPTIC_SWITCH)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (StringUtils.equalsIgnoreCase(<span class="string">"update"</span>, methodName)</span><br><span class="line">                    || StringUtils.equalsIgnoreCase(<span class="string">"insert"</span>, methodName)) &#123;</span><br><span class="line">                CryptPojoUtils.encryptField(parameter);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Object returnValue = invocation.proceed();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (!<span class="string">"0"</span>.equals(CRYPTIC_SWITCH)) &#123;</span><br><span class="line">                <span class="keyword">if</span> (returnValue <span class="keyword">instanceof</span> ArrayList&lt;?&gt;) &#123;</span><br><span class="line">                    List&lt;?&gt; list = (ArrayList&lt;?&gt;) returnValue;</span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">null</span> == list || <span class="number">1</span> &gt; list.size())</span><br><span class="line">                        <span class="keyword">return</span> returnValue;</span><br><span class="line">                    Object obj = list.get(<span class="number">0</span>);</span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">null</span> == obj)  <span class="comment">// 这里虽然list不是空，但是返回字符串等有可能为空</span></span><br><span class="line">                        <span class="keyword">return</span> returnValue;</span><br><span class="line">                    <span class="comment">// 判断第一个对象是否有DecryptField注解</span></span><br><span class="line">                    Field[] fields = obj.getClass().getDeclaredFields();</span><br><span class="line">                    <span class="keyword">int</span> len;</span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">null</span> != fields &amp;&amp; <span class="number">0</span> &lt; (len = fields.length)) &#123;</span><br><span class="line">                        <span class="comment">// 标记是否有解密注解</span></span><br><span class="line">                        <span class="keyword">boolean</span> isD = <span class="keyword">false</span>;</span><br><span class="line">                        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">                            <span class="comment">/**</span></span><br><span class="line"><span class="comment">                             * 由于返回的是同一种类型列表，因此这里判断出来之后可以保存field的名称</span></span><br><span class="line"><span class="comment">                             * 之后处理所有对象直接按照field名称查找Field从而改之即可</span></span><br><span class="line"><span class="comment">                             * 有可能该类存在多个注解字段，所以需要保存到数组（项目中目前最多是2个）</span></span><br><span class="line"><span class="comment">                             * <span class="doctag">@TODO</span> 保存带DecryptField注解的字段名称到数组，按照名称获取字段并解密</span></span><br><span class="line"><span class="comment">                             * */</span></span><br><span class="line">                            <span class="keyword">if</span> (fields[i].isAnnotationPresent(DecryptField.class)) &#123;</span><br><span class="line">                                isD = <span class="keyword">true</span>;</span><br><span class="line">                                <span class="keyword">break</span>;</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125; <span class="comment">/// for end ~</span></span><br><span class="line">                        <span class="keyword">if</span> (isD)  <span class="comment">// 将含有DecryptField注解的字段解密</span></span><br><span class="line">                            list.forEach(l -&gt; CryptPojoUtils.decryptField(l));</span><br><span class="line">                    &#125; <span class="comment">/// if end ~</span></span><br><span class="line">                &#125; <span class="comment">/// if end ~</span></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="comment">// 打印异常，由于拦截器本身抛出异常，比如拦截到很奇葩的返回，应算正常</span></span><br><span class="line">            <span class="comment">// 直接返回原结果即可</span></span><br><span class="line">            logger.info(<span class="string">"抛出异常，正常返回==&gt; "</span> + e.getMessage());</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            <span class="keyword">return</span> returnValue;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> returnValue;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">plugin</span><span class="params">(Object target)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Plugin.wrap(target, <span class="keyword">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setProperties</span><span class="params">(Properties properties)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="不同框架配置说明"><a href="#不同框架配置说明" class="headerlink" title="不同框架配置说明"></a>不同框架配置说明</h2><h3 id="springboot下的配置"><a href="#springboot下的配置" class="headerlink" title="springboot下的配置"></a>springboot下的配置</h3><ul>
<li>启动主类需要添加mapper扫描注解</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="meta">@MapperScan</span>(<span class="string">"git.yampery.cryptic.dao"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Application</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		SpringApplication.run(Application.class, args);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>配置文件application.properties需要添加映射</li>
</ul>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Mybatis</span></span><br><span class="line">mybatis.config-location             =classpath:mybatis/mybatis-config.xml</span><br><span class="line">mybatis.mapper-locations            =classpath:mybatis/mapper/*.xml</span><br><span class="line">mybatis.type-aliases-package        =git.yampery.cryptic.pojo</span><br><span class="line"></span><br><span class="line"><span class="comment"># 开启debug模式可以在控制台查看springboot加载流程</span></span><br><span class="line"><span class="comment"># debug                               =true</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 密盐（使用工具ADESUtils生成）</span></span><br><span class="line">sys.aes.salt                        =4BB90812C2B9B0882A6FA7C203E4717F</span><br><span class="line"><span class="comment"># 加解密开关（1：开启加解密；0：关闭加解密）</span></span><br><span class="line">sys.aes.switch                      =1</span><br></pre></td></tr></table></figure>
<ul>
<li>拦截器会自动扫描，注意@Component注解</li>
</ul>
<h3 id="spring的xml配置"><a href="#spring的xml配置" class="headerlink" title="spring的xml配置"></a>spring的xml配置</h3><ul>
<li>mybatis当然和传统配置一致，在spring上下文配置中添加</li>
<li>拦截器配置，在spring上下文配置文件sqlsessionfactory中</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"sqlSessionFactory"</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.SqlSessionFactoryBean"</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"dataSource"</span> /&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"configLocation"</span> <span class="attr">value</span>=<span class="string">"classpath:mybatis.xml"</span> /&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- 自动扫描mapping.xml文件 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"mapperLocations"</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">array</span>&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">value</span>&gt;</span>classpath:mybatis/mapper/*.xml<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;/<span class="name">array</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"plugins"</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">array</span>&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"git.yampery.cryptic.interceptor.DBInterceptor"</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"properties"</span> <span class="attr">value</span>=<span class="string">"property-value"</span>/&gt;</span></span><br><span class="line">			<span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;/<span class="name">array</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.mapper.MapperScannerConfigurer"</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"basePackage"</span> <span class="attr">value</span>=<span class="string">"git.yampery.cryptic.dao"</span> /&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"sqlSessionFactoryBeanName"</span> <span class="attr">value</span>=<span class="string">"sqlSessionFactory"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="说明"><a href="#说明" class="headerlink" title="说明"></a>说明</h2><p><strong>注意：文章中的代码只是部分，源码包含完整的测试和说明，<a href="https://github.com/Yampery/cryptic-data" target="_blank" rel="noopener">点击访问项目源码。</a></strong></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/01/05/ambari/" rel="next" title="ambari搭建大数据平台">
                <i class="fa fa-chevron-left"></i> ambari搭建大数据平台
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/05/docker_elk/" rel="prev" title="基于docker搭建ELK系统">
                基于docker搭建ELK系统 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">yampery</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/yampery" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:1yampery@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#加解密工具"><span class="nav-number">1.</span> <span class="nav-text">加解密工具</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#加解密字段注解"><span class="nav-number">2.</span> <span class="nav-text">加解密字段注解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#加密注解"><span class="nav-number">2.1.</span> <span class="nav-text">加密注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#解密注解"><span class="nav-number">2.2.</span> <span class="nav-text">解密注解</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#封装加解密工具"><span class="nav-number">3.</span> <span class="nav-text">封装加解密工具</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#拦截器"><span class="nav-number">4.</span> <span class="nav-text">拦截器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#不同框架配置说明"><span class="nav-number">5.</span> <span class="nav-text">不同框架配置说明</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#springboot下的配置"><span class="nav-number">5.1.</span> <span class="nav-text">springboot下的配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#spring的xml配置"><span class="nav-number">5.2.</span> <span class="nav-text">spring的xml配置</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#说明"><span class="nav-number">6.</span> <span class="nav-text">说明</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yampery</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">NexT.Mist</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("35rGUMRzp5wPN2jmmIUWeBNh-gzGzoHsz", "fmF6mJDmgl0FkqBKX8I2HiGF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
